package com.threadpool.pool.queue;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 无界队列
 * </p>
 *
 * @author 桌角的眼镜
 * @version 1.0
 * @since 2025/5/14 0:50
 */
public class UnboundedQueue<T> implements CustomBlockingQueue<T> {
    private final LinkedList<T> queue = new LinkedList<>();

    @Override
    public synchronized boolean offer(T task) {
        queue.addLast(task);
        notifyAll();
        return true;
    }

    @Override
    public synchronized T poll(long timeout, TimeUnit unit) {
        while (queue.isEmpty()) {
            try {
                wait(unit.toMillis(timeout));
            } catch (InterruptedException e) {
                return null;
            }
        }
        return queue.removeFirst();
    }

    @Override
    public synchronized T poll() {
        return queue.isEmpty() ? null : queue.removeFirst();
    }
}
